package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.DatasetRecord;
import com.micro.ai.models.mapper.DatasetRecordMapper;
import com.micro.ai.models.service.DatasetRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据集记录服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class DatasetRecordServiceImpl extends ServiceImpl<DatasetRecordMapper, DatasetRecord> implements DatasetRecordService {

    @Override
    public Page<DatasetRecord> pageQuery(int pageNum, int pageSize, String tenantId, String datasetId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<DatasetRecord> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DatasetRecord> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(DatasetRecord::getTenantId, tenantId);
        }
        if (StringUtils.hasText(datasetId)) {
            query.eq(DatasetRecord::getDatasetId, datasetId);
        }
        
        query.orderByAsc(DatasetRecord::getRecordIndex);
        
        return this.page(page, query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatasetRecord create(DatasetRecord record) {
        if (record == null) {
            throw new BusinessException("M0000", "记录信息不能为空");
        }
        
        if (!StringUtils.hasText(record.getDatasetId())) {
            throw new BusinessException("M0000", "数据集ID不能为空");
        }
        
        // 如果没有指定索引，自动计算下一个索引
        if (record.getRecordIndex() == null) {
            LambdaQueryWrapper<DatasetRecord> query = new LambdaQueryWrapper<>();
            query.eq(DatasetRecord::getDatasetId, record.getDatasetId())
                 .orderByDesc(DatasetRecord::getRecordIndex)
                 .last("LIMIT 1");
            
            DatasetRecord lastRecord = this.getOne(query);
            int nextIndex = lastRecord != null ? lastRecord.getRecordIndex() + 1 : 1;
            record.setRecordIndex(nextIndex);
        }
        
        if (record.getIsValid() == null) {
            record.setIsValid(true);
        }
        
        record.setCreatedAt(LocalDateTime.now());
        
        boolean success = this.save(record);
        if (!success) {
            throw new BusinessException("M0003", "保存记录失败");
        }
        
        log.info("创建数据集记录成功: recordId={}, datasetId={}, index={}", 
                record.getId(), record.getDatasetId(), record.getRecordIndex());
        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DatasetRecord> batchCreate(List<DatasetRecord> records, String datasetId) {
        if (records == null || records.isEmpty()) {
            throw new BusinessException("M0000", "记录列表不能为空");
        }
        if (!StringUtils.hasText(datasetId)) {
            throw new BusinessException("M0000", "数据集ID不能为空");
        }
        
        // 获取当前最大索引
        LambdaQueryWrapper<DatasetRecord> query = new LambdaQueryWrapper<>();
        query.eq(DatasetRecord::getDatasetId, datasetId)
             .orderByDesc(DatasetRecord::getRecordIndex)
             .last("LIMIT 1");
        
        DatasetRecord lastRecord = this.getOne(query);
        int startIndex = lastRecord != null ? lastRecord.getRecordIndex() + 1 : 1;
        
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < records.size(); i++) {
            DatasetRecord record = records.get(i);
            record.setDatasetId(datasetId);
            if (record.getRecordIndex() == null) {
                record.setRecordIndex(startIndex + i);
            }
            if (record.getIsValid() == null) {
                record.setIsValid(true);
            }
            record.setCreatedAt(now);
        }
        
        boolean success = this.saveBatch(records);
        if (!success) {
            throw new BusinessException("M0003", "批量保存记录失败");
        }
        
        log.info("批量创建数据集记录成功: datasetId={}, count={}", datasetId, records.size());
        return records;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatasetRecord update(String id, DatasetRecord record) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "记录ID不能为空");
        }
        if (record == null) {
            throw new BusinessException("M0000", "记录信息不能为空");
        }
        
        DatasetRecord existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "记录不存在: " + id);
        }
        
        record.setId(id);
        
        boolean success = this.updateById(record);
        if (!success) {
            throw new BusinessException("M0003", "更新记录失败");
        }
        
        log.info("更新数据集记录成功: recordId={}", id);
        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "记录ID不能为空");
        }
        
        DatasetRecord record = this.getById(id);
        if (record == null) {
            throw new BusinessException("M0002", "记录不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除记录失败");
        }
        
        log.info("删除数据集记录成功: recordId={}, datasetId={}, index={}", 
                id, record.getDatasetId(), record.getRecordIndex());
    }

    @Override
    public List<DatasetRecord> listByDatasetId(String datasetId) {
        if (!StringUtils.hasText(datasetId)) {
            return new ArrayList<>();
        }
        
        LambdaQueryWrapper<DatasetRecord> query = new LambdaQueryWrapper<>();
        query.eq(DatasetRecord::getDatasetId, datasetId)
             .orderByAsc(DatasetRecord::getRecordIndex);
        
        return this.list(query);
    }
}

